/*
 * Created by Jaren at 2021/10/28 17:49
 */
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jieli_ble_ota_plugin_example/base/base.dart';
import 'package:jieli_ble_ota_plugin_example/search/search_controller.dart';

class SearchPage extends BaseView<SearchController> {

    @override
    Widget build(BuildContext context) {
        super.build(context);
        return Scaffold(
            appBar: AppBar(
                title: const Text("Scan Device"),
                actions: [
                    Obx(() =>
                        TextButton(
                            child: Text(controller.searching.value ? 'STOP' : 'SCAN',
                                style: const TextStyle(color: Color.fromARGB(0xFF, 0xFF, 0xFF, 0xFF)),),
                            style: TextButton.styleFrom(
                                textStyle: const TextStyle(fontSize: 20),
                            ),
                            onPressed: _handleScanBtnClick(controller)))
                ],
            ),
            body: Column(
                children: [
                    Expanded(
                        child: Obx(() =>
                            RefreshIndicator(
                                onRefresh: () async {
                                    controller.devices.clear();
                                    controller.scan();
                                },
                                child: controller.isLoading.value ? const CircularProgressIndicator(strokeWidth: 5,) : _buildListView(controller),
                            ),
                        ),
                    ),
                ],
            )
        );
    }

    _handleScanBtnClick(controller) {
        if (controller.btState.value == false) return;
        if (controller.searching.value) {
            controller.stopScanning();
        } else {
            controller.scan();
        }
    }

    _handleDeviceItemClick(controller, {device, id}) {
    controller.connect(device: device, identify: id);
  }

    _buildListView(controller) {
        return ListView.builder(
            itemCount: controller.devices.length,
            itemBuilder: (context, index) {
                final item = controller.devices[index];
                return ListTile(
                    onTap: () => _handleDeviceItemClick(controller, id: item.id.id),
                    title: Text(item.name),
                    subtitle: Text(item.id.id),
                );
            },
        );
    }

}